﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using popLib;
using popLib.ExtensionClass;
using PhotoMgr.src.database;
using PhotoMgr.src.common;
using System.IO;
using System.Threading;

namespace PhotoMgr.src.gui.photo
{
    public partial class HostForm : Form
    {
        SocketServer server;
        Contest contest;
        Round round;

        List<ClienList> clients;
        List<View_RoundImage> images;
        int SelectedRoundImageID = -1; //hinh dang duoc chon de xem tren cac may
        int SelectedRowIndex = -1;
        int ViewRoundImageID = -1; //hinh QSV dang xem
        int ViewRowIndex = -1;
        ScoreType scoretype;

        public enum ScoreType { MainScore, SubScore, ThirdScore }

        public HostForm(int contestID, ScoreType scoreType)
        {
            InitializeComponent();

            clients = new List<ClienList>();
            images = new List<View_RoundImage>();
            scoretype = scoreType;

            dataGridView1.AutoGenerateColumns = false;
            Global.InitDataGridView(dataGridView1, new DataGridViewColumn[] { 
                Global.GenColumn("Giám khảo", "Username").SetSizeMode(DataGridViewAutoSizeColumnMode.Fill),
                Global.GenColumn("Điểm", scoretype == ScoreType.MainScore ? "Score" : scoretype == ScoreType.SubScore ? "SubScore" : "ThirdScore" ),
                Global.GenColumn("IPAddress", "IPAddress").SetVisible(false),
                
            });

            dataGridView2.AutoGenerateColumns = false;
            Global.InitDataGridView(dataGridView2, new DataGridViewColumn[] { 
                Global.GenColumn("#", scoretype == ScoreType.MainScore ? "IsScore" : scoretype == ScoreType.SubScore ? "IsSubScore" : "IsThirdScore", Global.GenColumnType.CheckBox),
                Global.GenColumn("Hình ảnh", "ImageTitle").SetSizeMode(DataGridViewAutoSizeColumnMode.Fill),
                Global.GenColumn("Điểm", scoretype == ScoreType.MainScore ? "Score" : scoretype == ScoreType.SubScore ? "SubScore" : "ThirdScore"),
                Global.GenColumn(" ", "RoundImageID").SetVisible(false),
            });

            ReturnSet rs = DBManager.Detail_ContestTrung(contestID);
            if (rs.Success)
            {
                contest = (Contest)rs.Result;

                ReturnSet rs1 = DBManager.Contest_GetAvailableRound(contest.ContestID);
                if (rs1.Success)
                {
                    round = (Round)rs1.Result;
                    LoadImageList();
                }
                else
                {
                    FormLib.alert("Không tìm thấy vòng loại nào cho cuộc thi này!!");
                    this.Opacity = 0;
                    FormLib.ExitTimer(this, 100);
                }
            }
            else
            {
                FormLib.alert("Không tìm thấy cuộc thi này!!");
                this.Opacity = 0;
                FormLib.ExitTimer(this, 100);
            }

            server = new SocketServer(9889);
            server.ConnectionStatusChangedEvent += new ClientHandler.ConnectionStatusChanged(server_ConnectionStatusChangedEvent);
            server.ReceiveMessageEvent += new ClientHandler.ReceiveMessage(server_ReceiveMessageEvent);
            server.Start();

            
        }


        void UpdateDGVSource()
        {
            ThreadStart a = delegate
            {
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = clients;

                dataGridView2.DataSource = null;
                dataGridView2.DataSource = images;

                for (int i = 0; i < dataGridView2.Rows.Count; i++)
                {
                    if (i == SelectedRowIndex)
                    {
                        dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    }
                    else if (i == ViewRowIndex)
                    {
                        dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
                    }                     
                    else
                    {
                        dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.Empty;
                    }
                }
            };
            this.Invoke(a);
        }

        void server_ReceiveMessageEvent(ClientHandler client, string message)
        {
            string[] items = message.Split(';');
            switch (items[0])
            {
                case "LOGIN":
                    string username = items[1];
                    string userid = items[2];
                    var rs = clients.Where(x => x.IPAddress == client.IP);
                    if (rs.Count() > 0)
                    {
                        rs.First().Username = username;
                        rs.First().UserID = NumberLib.getInt(userid);
                        UpdateDGVSource();
                    }

                    //check if correct user
                    server.SendMessage(client.IP, "ACCEPTED");
                    //else REJECT

                    break;
                case "UPDATE":
                    UpdateScore(SelectedRoundImageID);
                    break;
            }
        }

        void server_ConnectionStatusChangedEvent(ClientHandler client, bool isConnected)
        {
            if (isConnected)
            {
                clients.Add(new ClienList() { IPAddress = client.IP, Username = "", Score = 0 });
                server.SendMessage(client.IP, "LOGIN");
            }
            else
            {
                var rs = clients.Where(x => x.IPAddress == client.IP);
                if (rs.Count() > 0)
                {
                    clients.Remove(rs.First());
                }
            }

            //UpdateDGVSource();
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            server.SendMessageBroadcast("START");
        }
        
        

        private void btn_pause_Click(object sender, EventArgs e)
        {
            server.SendMessageBroadcast("PAUSE");
        }

        private void btn_end_Click(object sender, EventArgs e)
        {
            server.SendMessageBroadcast("END");
        }

        void UpdateScore(int roundImageID)
        {
            double avgScore = 0;

            foreach (var item1 in clients)
            {
                item1.Score = 0;
            }

            List<ImageScore> list = DBManager.ImageScore_ViewScore(roundImageID);
            foreach (var item in list)
            {
                foreach (var item1 in clients)
                {
                    if (item1.UserID == item.UserID)
                    {
                        item1.Score = (double)item.Score;
                        avgScore += (double)item.Score;
                    }
                }
            }

            var rs = images.Where(x => x.RoundImageID == roundImageID);
            if (rs.Count() > 0)
            {
                rs.First().Score = avgScore;
            }

            if (DBManager.ImageScore_IsScoreAll(roundImageID) > 0)
            {
                button1_Click(null, new EventArgs());
            }

            UpdateDGVSource();
        }

        void LoadImageList() {
            images = DBManager.RoundImage_ListByRoundID(round.RoundID);                        
        }

        private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int roundImageID = NumberLib.getInt( dataGridView2.Rows[e.RowIndex].Cells[3].Value );

            ViewRowIndex = e.RowIndex;            
            
            DisplayImageInfo(roundImageID);
        }


        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            SelectedRoundImageID = ViewRoundImageID;
            SelectedRowIndex = ViewRowIndex;
            ViewImageBroadcast(SelectedRoundImageID);
        }

        void ViewImageBroadcast(int roundImageID)
        {
            var rs = images.Where(x => x.RoundImageID == roundImageID);
            View_RoundImage img = rs.First();

            //title, artist, note, path, roundimageid
            string message = string.Format("VIEW;{0}", roundImageID);
            server.SendMessageBroadcast( message );

            //UpdateScore(roundImageID);

            DisplayImageInfo(roundImageID);
        }

        void DisplayImageInfo(int roundImageID)
        {
            var rs = images.Where(x => x.RoundImageID == roundImageID);
            View_RoundImage img = rs.First();

            string file = Path.Combine(Configuration.Instance.ServerPath, img.ImagePath);

            pictureBox1.Image = System.Drawing.Image.FromFile(file);
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

            lbl_imageTitle.Text = img.ImageTitle;
            lbl_artistName.Text = "Tác giả: " + img.ArtistName;
            lbl_note.Text = "";

            ViewRoundImageID = img.RoundImageID;

            UpdateScore(img.RoundImageID);

            GC.Collect();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (SelectedRowIndex < images.Count - 1)
            {                
                SelectedRowIndex++;
                SelectedRoundImageID = NumberLib.getInt( dataGridView2.Rows[SelectedRowIndex].Cells[3].Value );
                ViewImageBroadcast(SelectedRoundImageID);
            }
        }
    }

    

    
}
